package com.zhiche.lisa.tms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.sun.corba.se.spi.ior.ObjectId;
import com.zhiche.lisa.config.TmsProperties;
import com.zhiche.lisa.core.enums.IntegrationURIEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.qiniu.config.QiniuConfig;
import com.zhiche.lisa.core.utils.qiniu.util.QiniuUtils;
import com.zhiche.lisa.tms.dao.mapper.ShipmentAttachMapper;
import com.zhiche.lisa.tms.dao.model.Shipment;
import com.zhiche.lisa.tms.dao.model.ShipmentAttach;
import com.zhiche.lisa.tms.dao.model.ShipmentAttachHistory;
import com.zhiche.lisa.tms.service.IShipmentAttachHistoryService;
import com.zhiche.lisa.tms.service.IShipmentAttachService;
import com.zhiche.lisa.tms.service.IShipmentService;
import com.zhiche.lisa.tms.vo.PhotoVO;
import io.jsonwebtoken.lang.Collections;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.message.BasicNameValuePair;
import org.assertj.core.util.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 * 运单附件表 服务实现类
 * </p>
 *
 * @author qichao
 * @since 2018-08-16
 */
@Service
public class ShipmentAttachServiceImpl extends ServiceImpl<ShipmentAttachMapper, ShipmentAttach> implements IShipmentAttachService {

    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier(value = "shipmentAttachHistoryServiceImpl")
    IShipmentAttachHistoryService shipmentAttachHistoryService;

    @Autowired private QiniuConfig qiniuConfig;
    @Autowired private IShipmentService shipmentService;
    @Autowired private TmsProperties properties;

    @Override
    public void photo(PhotoVO photoVO, String token) {
        if(StringUtils.isEmpty(photoVO.getAttachKey())){
            throw new BaseException(-1,"照片Key不能为空！");
        }
        if(StringUtils.isEmpty(photoVO.getAttachName())){
            throw new BaseException(-1,"照片名不能为空！");
        }
        if(StringUtils.isEmpty(photoVO.getAttachType())){
            throw new BaseException(-1,"照片类型不能为空！");
        }
        if(StringUtils.isEmpty(photoVO.getShipmentCode())){
            throw new BaseException(-1,"运单code不能为空！");
        }
        if(StringUtils.isEmpty(photoVO.getShipTaskCode())){
            throw new BaseException(-1,"任务code不能为空！");
        }
        ShipmentAttach shipmentAttachInfo=new ShipmentAttach();
        shipmentAttachInfo.setAttachKey(photoVO.getAttachKey());
        shipmentAttachInfo.setAttachName(photoVO.getAttachName());
        shipmentAttachInfo.setAttachType(photoVO.getAttachType());
        shipmentAttachInfo.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        shipmentAttachInfo.setShipmentCode(photoVO.getShipmentCode());
        shipmentAttachInfo.setShipTaskCode(photoVO.getShipTaskCode());
        shipmentAttachInfo.setPurpose(photoVO.getPurpose());
        if(!StringUtils.isEmpty(photoVO.getDataSources())){
            shipmentAttachInfo.setDataSources(photoVO.getDataSources());
        }else {// 默认微信公众号
            shipmentAttachInfo.setDataSources("微信公众号");
        }
        Wrapper<ShipmentAttach> shipmentAttachWrapper=new EntityWrapper<>();
        shipmentAttachWrapper.eq("ship_task_code",photoVO.getShipTaskCode());
        shipmentAttachWrapper.eq("purpose",photoVO.getPurpose());
        // 发运照片是否审核
        List<ShipmentAttach>  shipmentAttachs = this.selectList(shipmentAttachWrapper);
        if(null != shipmentAttachs && !shipmentAttachs.isEmpty()){
            for(ShipmentAttach shipmentAttach1 : shipmentAttachs){
                // 微信端可以上传
                if(!"微信公众号".equals(shipmentAttachInfo.getDataSources()) && 1 == shipmentAttach1.getAuthStatus()){
                    // 照片审核之后PC端不能在上传
                    throw new BaseException(-1,"照片已审核！请取消审核在上传！");
                }
            }
        }
        shipmentAttachWrapper.eq("attach_type",photoVO.getAttachType());
        ShipmentAttach  shipmentAttach=this.selectOne(shipmentAttachWrapper);
        if (shipmentAttach == null){
            this.insert(shipmentAttachInfo);
            //当这五个值有变化时更新图片表同时把老数据插入图片历史表
        } else if (!shipmentAttach.getPurpose().equals(photoVO.getPurpose()) || !shipmentAttach.getShipmentCode().equals(photoVO.getShipmentCode())
                || !photoVO.getShipTaskCode().equals(shipmentAttach.getShipTaskCode()) || !shipmentAttach.getAttachKey().equals(photoVO.getAttachKey())
                || !shipmentAttach.getAttachType().equals(photoVO.getAttachType())) {
            // 是pc上传，更新照片。附件表不是PC的也更新
            if("pc".equals(photoVO.getDataSources()) || !"pc".equals(shipmentAttach.getDataSources())){
                shipmentAttachInfo.setId(shipmentAttach.getId());
                this.updateById(shipmentAttachInfo);
            }

            ShipmentAttachHistory shipmentAttachHistory = new ShipmentAttachHistory();
            shipmentAttachHistory.setAttachKey(shipmentAttach.getAttachKey());
            shipmentAttachHistory.setAttachName(shipmentAttach.getAttachName());
            shipmentAttachHistory.setAttachType(shipmentAttach.getAttachType());
            shipmentAttachHistory.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            shipmentAttachHistory.setPurpose(shipmentAttach.getPurpose());
            shipmentAttachHistory.setShipmentCode(shipmentAttach.getShipmentCode());
            shipmentAttachHistory.setShipTaskCode(shipmentAttach.getShipTaskCode());
            if(!StringUtils.isEmpty(shipmentAttach.getDataSources())){
                shipmentAttachHistory.setDataSources(shipmentAttach.getDataSources());
            }else {// 默认微信公众号
                shipmentAttachHistory.setDataSources("微信公众号");
            }
            if("pc".equals(shipmentAttach.getDataSources()) && !"pc".equals(photoVO.getDataSources())){
                shipmentAttachHistory.setAttachKey(photoVO.getAttachKey());
                shipmentAttachHistory.setAttachName(photoVO.getAttachName());
                shipmentAttachHistory.setAttachType(photoVO.getAttachType());
                shipmentAttachHistory.setPurpose(photoVO.getPurpose());
                shipmentAttachHistory.setShipmentCode(photoVO.getShipmentCode());
                shipmentAttachHistory.setShipTaskCode(photoVO.getShipTaskCode());
                shipmentAttachHistory.setDataSources("微信公众号");
            }
            Wrapper<ShipmentAttachHistory> shipmentAttachHistoryWrapper = new EntityWrapper<>();
            shipmentAttachHistoryWrapper.eq("ship_task_code", photoVO.getShipTaskCode());
            shipmentAttachHistoryWrapper.eq("attach_type",photoVO.getAttachType());
            shipmentAttachHistoryWrapper.eq("shipment_code",photoVO.getShipmentCode());
            shipmentAttachHistoryWrapper.eq("purpose",photoVO.getPurpose());
            shipmentAttachHistoryWrapper.eq("attach_key",photoVO.getAttachKey());
            ShipmentAttachHistory shipmentAttachHistoryDate= shipmentAttachHistoryService.selectOne(shipmentAttachHistoryWrapper);
            if (shipmentAttachHistoryDate==null){
                shipmentAttachHistoryService.insert(shipmentAttachHistory);
            } else {
                shipmentAttachHistory.setId(shipmentAttachHistoryDate.getId());
                shipmentAttachHistoryService.updateById(shipmentAttachHistory);
            }
        }

    }

    private String getShipToKeys(List<ShipmentAttach> shipmentAttachs) {
        // 拿取运抵照片key
        StringBuffer shipToKeysBuffer = new StringBuffer();
        for (ShipmentAttach shipmentAttach : shipmentAttachs) {
            shipToKeysBuffer.append(shipmentAttach.getAttachKey() + ",");
        }
        return String.valueOf(shipToKeysBuffer.substring(0, shipToKeysBuffer.length() - 1));
    }

    @Override
    public void updateAttachAuthStatus(Map<String, Object> code,String token) {
        String shipmentCode= (String)code.get("code");
        String authStatus= (String)code.get("authStatus");
        if(StringUtils.isEmpty(shipmentCode)){
            throw new BaseException(-1,"装车单号不能为空！");
        }
        if(null == authStatus || StringUtils.isEmpty(authStatus)){
            authStatus = "1";
        }
        String[] split = shipmentCode.split(",");
        List<String> shipmentCodes = Arrays.asList(split);

        Wrapper<ShipmentAttach> shipmentAttachWrapper=new EntityWrapper<>();
        shipmentAttachWrapper.in("shipment_code",shipmentCodes)
                .eq("purpose","10");

        ShipmentAttach shipmentAttach = new ShipmentAttach();
        shipmentAttach.setAuthStatus(Integer.valueOf(authStatus));
        baseMapper.update(shipmentAttach,shipmentAttachWrapper);

        // 取消审核返回
        if("0".equals(authStatus)){return;}

        // 审核照片推送OTM
        for(String shipCode : shipmentCodes){
            Wrapper<ShipmentAttach> attachWp =new EntityWrapper<>();
            attachWp.eq("shipment_code",shipCode)
//                .eq("attach_type",photoVO.getAttachType());
                    .eq("purpose","10");
            List<ShipmentAttach> shipmentAttachs = this.selectList(attachWp);
            if(null != shipmentAttachs && !shipmentAttachs.isEmpty()){
                Wrapper<Shipment> shipmentew =new EntityWrapper<>();
                shipmentew.eq("code",shipCode);
                List<Shipment> shipments = shipmentService.selectList(shipmentew);

                String shipToKeys = getShipToKeys(shipmentAttachs);

                HashMap<String, String> param = Maps.newHashMap();
                param.put("shipmentGid", shipments.get(0).getShipSourceKey());
                param.put("shipPicKeys", shipToKeys);
                param.put("departTime", DateUtils.formatDate(new Date(), "yyyy/MM/dd HH:mm:ss"));
                String jsonParam = JSONObject.toJSONString(param);
                ArrayList<NameValuePair> headers = Lists.newArrayList();
                headers.add(new BasicNameValuePair("Authorization", token));
                new Thread(() -> {
                    try {
                        logger.info("PC端审核发运图片--> 回传OTM url:{},param:{}", properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(),
                                jsonParam);
                        String resJson = HttpClientUtil.postJson(properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(),
                                headers, jsonParam, properties.getSocktTimeOut());
                        logger.info("departureConfirmation PC端审核发运图片,回传OTM响应结果:{}", resJson);
                    } catch (Exception e) {
                        logger.error("departureConfirmation PC端审核发运图片,回传OTM指超时异常:url:{},params:{}", properties.getIntegrationhost() + IntegrationURIEnum.TMS_SHIP_URI.getAddress(), jsonParam);
                    }
                }).start();
            }
        }

    }

    @Override
    public List<ShipmentAttach> queryShipAttachList(String code) {

        List<ShipmentAttach> shipmentAttachs = baseMapper.selectListJoinTask(code);
        List<ShipmentAttach> shipmentAttachs2 = new ArrayList<>();
        if(!Collections.isEmpty(shipmentAttachs)){
            shipmentAttachs.forEach(shipmentAttach ->{
                if(!StringUtils.isEmpty(shipmentAttach.getAttachKey())){
                    String url = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), shipmentAttach.getAttachKey());
                    if(!StringUtils.isEmpty(url)){
                        shipmentAttach.setDownloadPatch(url + "&attname=" + shipmentAttach.getAttachName());
                        shipmentAttach.setLookPatch(url);
                    }
                }
                int count = contrastValue(shipmentAttachs, shipmentAttach.getShipTaskCode());
                if(count == 1){
                    ShipmentAttach shipmentAttach2 = new ShipmentAttach();
                    shipmentAttach2.setShipTaskCode(shipmentAttach.getShipTaskCode());
                    shipmentAttach2.setShipmentCode(shipmentAttach.getShipmentCode());
                    if("01".equals(shipmentAttach.getAttachType())){
                        shipmentAttach2.setAttachType("02");
                        shipmentAttachs2.add(shipmentAttach2);
                    }else if("02".equals(shipmentAttach.getAttachType())){
                        shipmentAttach2.setAttachType("01");
                        shipmentAttachs2.add(shipmentAttach2);
                    }else{
                        shipmentAttach.setAttachType("01");
                        shipmentAttach2.setAttachType("02");
                        shipmentAttachs2.add(shipmentAttach2);
                    }
                }
            });
            if(null != shipmentAttachs2 && !shipmentAttachs2.isEmpty()){
                shipmentAttachs.addAll(shipmentAttachs2);
            }
        }
        return shipmentAttachs;
    }

    private int contrastValue(List<ShipmentAttach> shipmentAttachs, String shipTaskCode) {
        int i = 0;
        for (ShipmentAttach shipmentAttach : shipmentAttachs) {
            if(shipTaskCode.equals(shipmentAttach.getShipTaskCode())){
                i++;
            }
        }
        return i;
    }

    @Override
    public Map<String, Object> getShipAttachUrl(Map<String, Object> condition) {

        if(null == condition){ return null;}
        String attachKey = (String)condition.get("attachKey");
        String attachName = (String)condition.get("attachName");
        if(null == attachKey || "".equals(attachKey) || null == attachName || "".equals(attachName)){return null;}

        Map<String, Object> map = new HashMap<>();
        String url = QiniuUtils.generateDownloadTicket(qiniuConfig.getDownloadUrl(), attachKey);
        map.put("lookUrl",url);
        if(null != url && !"".equals(url)){
            map.put("downloadUrl",url + "&attname=" + attachName);
        }
        return map;
    }

    @Override
    public void deleteShipAttach(Long id) {
        if(null == id || "".equals(id)){return ;}

        ShipmentAttach shipmentAttach = baseMapper.selectById(id);
        if(null == shipmentAttach){return ;}

        Wrapper<ShipmentAttachHistory> shipmentAttachHistoryWrapper = new EntityWrapper<>();
        shipmentAttachHistoryWrapper.eq("ship_task_code", shipmentAttach.getShipTaskCode());
        shipmentAttachHistoryWrapper.eq("attach_type",shipmentAttach.getAttachType());
        shipmentAttachHistoryWrapper.eq("shipment_code",shipmentAttach.getShipmentCode());
        shipmentAttachHistoryWrapper.eq("purpose",shipmentAttach.getPurpose());
        shipmentAttachHistoryWrapper.eq("attach_key",shipmentAttach.getAttachKey());
        ShipmentAttachHistory shipmentAttachHistoryDate= shipmentAttachHistoryService.selectOne(shipmentAttachHistoryWrapper);
        if (shipmentAttachHistoryDate == null){
            ShipmentAttachHistory shipmentAttachHistory = new ShipmentAttachHistory();
            shipmentAttachHistory.setAttachKey(shipmentAttach.getAttachKey());
            shipmentAttachHistory.setAttachName(shipmentAttach.getAttachName());
            shipmentAttachHistory.setAttachType(shipmentAttach.getAttachType());
            shipmentAttachHistory.setCreator(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
            shipmentAttachHistory.setPurpose(shipmentAttach.getPurpose());
            shipmentAttachHistory.setShipmentCode(shipmentAttach.getShipmentCode());
            shipmentAttachHistory.setShipTaskCode(shipmentAttach.getShipTaskCode());
            shipmentAttachHistory.setDataSources(shipmentAttach.getDataSources());
            shipmentAttachHistory.setAuthStatus(shipmentAttach.getAuthStatus());
            shipmentAttachHistoryService.insert(shipmentAttachHistory);
        }
        baseMapper.deleteById(id);

        return ;
    }
}
